package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountService userAccountService;

	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		//	调用mapper 层方法;
		return rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {
		//  保存充值信息
		RechargeInfo rechargeInfo = new RechargeInfo();
		rechargeInfo.setUserId(userId);
		//   定义充值编号
		String  orderNo = UUID.randomUUID().toString().replaceAll("-", "");
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
		rechargeInfoMapper.insert(rechargeInfo);
		return orderNo;
	}

	@Override
	public void rechargePaySuccess(String orderNo) {
		// 修改充值明细信息
		RechargeInfo rechargeInfo = this.getRechargeInfo(orderNo);
		if (rechargeInfo == null && rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
			return;
		}
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
		this.updateById(rechargeInfo);
		//	2.	修改用户余额;
		userAccountMapper.updateAvailableAmount(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());
		//	3.	记录账户信息;
		userAccountService.addUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), orderNo);
	}
}
